/* 
 * File:   Codec.cpp
 * Author: max
 * 
 * Created on April 27, 2013, 5:20 PM
 */

#include "common_Codec.h"
#include <cstdio>

using namespace TP;

Codec::Codec() {
}

Codec::~Codec() {
}

string& Codec::codificar(string& pData, const uint8_t *pBuffer, const size_t pLongitudBuffer) throw (Excepcion&){

    std::stringstream ss;
    ss << std::hex << std::setfill('0');
    
    for (uint32_t i = 0; i < pLongitudBuffer; ++i)
    {
        ss << std::setw(2) << static_cast<unsigned>(pBuffer[i]);
    }    
    ss >> pData;    
    
    return pData;
}

uint8_t*& Codec::decodificar (uint8_t* &pBuffer, uint32_t &pLongitudBuffer, const string& pData) throw (Excepcion&){
    
    if (pData.length() % 2 != 0)
    {
        throw Excepcion ("La cadena de caracteres no posee una representacion de array de bytes valida.");
    }
    
    pLongitudBuffer = pData.length() / 2;
    pBuffer = new uint8_t [pLongitudBuffer];
    
    uint32_t indice;
    uint32_t byte;
    
    for (indice = 0; indice <pLongitudBuffer; indice++)
    {
        sscanf (pData.c_str() + 2 * indice, "%2x", &byte);
        pBuffer[indice] = byte;
    }
    
    return pBuffer;
}
